<template>
	<div class="sn-common-container ">
	  <div class="prcoss-container" v-show="!editMarkDown">
		<header>
		  <div class="sn-flex sn-row-center hidden-sm-and-down">
			<el-select v-model="isDelete" value-key="" placeholder="是否删除" @change="currentChange(1)" style="width: 120px;margin-right: 10px;"  filterable >
				<el-option :label="'全部'" :value="'all'"></el-option>
				<el-option :label="'已删除'" :value="true"></el-option>
				<el-option :label="'未删除'" :value="false"></el-option>
			</el-select>
			<el-input v-model="searchValue" placeholder="输入功能名称进行筛选" style="width: 200px" clearable
			  @keyup.enter.native="currentChange(1)" />
			<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-search"
			  @click="currentChange(1)">
			  搜索
			</el-button>
			<el-button type="primary" size="default" @click="addClassOpen()" class="sn-btn" icon="el-icon-plus">新增功能</el-button>
		  </div>
		  <div class="hidden-sm-and-up">
			<el-input v-model="searchValue" placeholder="输入功能名称进行筛选" style="width: 200px" clearable
			  @keyup.enter.native="currentChange(1)" />
			<el-button style="margin-left: 4px" type="primary" class="sn-btn" icon="el-icon-search"
			  @click="currentChange(1)">
			</el-button>
			<el-button type="primary" style="margin-left: 4px;" size="default" @click="addClassOpen()" class="sn-btn" >新增</el-button>
		  </div>
		</header>
		<section>
		  <div class="category-list sn-flex" v-loading="tableLoading" v-if="tabelData.length!==0">
			<div class="category-item sn-flex" v-for="item in tabelData" :key="item.id">
				<img :src="item.iconUrl" alt="" class="category-image">
			  	<div class="category-item-title sn-flex">
					<span class="category-item-text">功能名称：</span>
					<el-tooltip
						:content="item.name"
						placement="top"
						effect="light"
						:disabled="item.name.length < 10"
					>
						<p class="text-center">{{ item.name }}</p>
					</el-tooltip>
				</div>
				<!-- <div class="category-item-title sn-flex">
					<span class="category-item-text">功能介绍：</span>
					<span>{{ item.description }}</span>
				</div> -->
				<div class="category-item-title ">
					<span class="category-item-text">关联字段：</span>
					<span style="flex:1;">{{ item.target ||'无' }}</span>
				</div>
				<div class="category-item-title sn-flex sn-row-center">
					<el-button type="primary" size="mini" @click="editDetails(item)">编辑功能介绍</el-button>

					<!-- <span v-if="!isDelete">
						<el-button type="primary" size="mini" @click="editClassBtnClick(item)">修改</el-button>
						<el-button type="primary" class="sn-btn" size="mini" @click="delClassFn(item.id,false)">删除</el-button>
					</span>
					<span v-else>
						<el-button type="primary" size="mini" @click="resetDeleteFn(item.id)">恢复</el-button>
							<el-button type="primary" size="mini" class="sn-btn" @click="delClassFn(item.id,true)">彻底删除</el-button>
					</span> -->
				</div>
			</div>
		  </div>
		  <div class="sn-flex sn-row-center" style="height: 400px;width: 100%;" v-else>
			<p>您还没有创建任何功能，请点击“新建功能” 去添加吧~</p>
		</div>
		</section>
		<footer>
		  <el-pagination @current-change="currentChange" :current-page.sync="currentPage" :page-size="pageSize"
			layout="prev, pager, next, jumper" :pager-count="7" class="sn-pagination" hide-on-single-pageww
			style="text-align: center;" :total="totalNum" background>
			>
		  </el-pagination>
		</footer>
	  </div>
	  <!-- 编辑或新增弹窗 -->
	  <el-dialog :visible.sync="editClassDialog" class="sn-default-dialog" width="360px" @close="classDialogClose()">
		<div class="sn-title" slot="title">{{editClassTitle}}</div>
		<div v-loading="editClassLoading">
		  <p style="margin-top: 0;">功能名称：</p>
		  <el-input v-model="editClassData.name" placeholder="请输入功能名称" style=""></el-input>
		  <!-- <p >功能Icon：</p>
		  <global-upload v-if="editClassDialog" :key="'front+dasda'"
			:isIdcardFront="true" @imageUpload="classIconUploadFn" @imageRemove="classIconRemoveFn"
			:initOne="editClassData.iconUrl" :isHeadImg="true">
			</global-upload> -->
		  <!-- <p >功能介绍：</p>
		  <el-input type="textarea" v-model="editClassData.description" placeholder="请输入功能介绍" style=""></el-input> -->
		  <p>关联字段：</p>
		  <el-input v-model="editClassData.target" placeholder="请输入关联字段" style=""></el-input>
		  <p style="text-align: center;">
			<el-button type="primary" size="medium" class="sn-btn" @click="saveClassInfoFn()">保存</el-button>
			<el-button size="medium" @click="editClassDialog = false">取消</el-button>
		  </p>
		</div>
	  </el-dialog>
	  <div v-show="editMarkDown" v-loading="markdownLoading">
		<div class="sn-flex sn-row-center">
			<h3 style="text-align:center;margin-right: 20px;">正在编辑功能"{{editItem.name}}" </h3>
			<h3 style="text-align:center;margin-right: 20px;">Ctrl+s 保存功能信息 </h3>
			<el-button class="sn-btn" @click="saveFn">保存</el-button>
			<el-button class="sn-btn" @click="editMarkDown = false">关闭编辑功能信息窗口</el-button>
		</div>
		<!-- autoSave -->
			<Markdown v-if="editMarkDown" :value="editItem.description"  :toolbars="toolbars" @on-save="markdownSave" @on-ready="markDownReadyFn" @on-upload-image="markDownUploadFn"/>
	  </div>
	</div>
  </template>
  
  <script>
  import GlobalTable from '@/components/GlobalTable';
  import GlobalUpload from '@/components/GlobalUpload';
  import { RestoreDeleteData } from '@/api/user';
  import {GetAllFunctions,AddFunction,UpdateFunction,DeleteFunction} from '@/api/enterprise'
import {uploadAvatar} from '@/api/user'

  import Markdown from 'vue-meditor'
  export default {
	components: { GlobalTable,GlobalUpload,Markdown },
	data() {
	  return {
		isDelete:false,
		tableLoading:false,
		tabelData: [],
		currentPage: 1,
		pageSize: 12,
		totalNum: 0,
		searchValue: '',
		editClassDialog: false,
		editClassLoading: false,
		editClassTitle:'',
		editClassData:{},
		markdownText:"",
		editMarkDown:false,
		markdownLoading:false,
		editItem:{},
		markdownDom:'',
		toolbars:{
			uploadImage:true	
		}
	  }
	},
	created() {
	  this.getDataListFn();
	},
	methods: {
		saveFn(){
			this.markdownDom.vm.handleSave();
		},
		editDetails(item){
			this.editItem = item;
			this.editMarkDown = true;
		},
		markDownReadyFn(markdown){
			this.markdownDom = markdown;
		},
		async markDownUploadFn(val){
			let formData = new FormData()
     		formData.append('file', val, 'avatar.jpg');
			const res = await uploadAvatar(formData);
			if(res.code === 200){
				this.markdownDom.insertContent(`![image](${res.data[0].url})`);
			}else{
				this.$message.error('上传失败，错误信息：'+res.erroMessage);
			}
		},
		async markdownSave(data){
			this.editItem.description = data.value;
			const res = await UpdateFunction(this.editItem);
			if(res.code === 200){
				this.$message({
					type: 'success',
					message: '保存成功!'
				});
			}else{
				this.$message.error('保存失败，错误信息：'+res.erroMessage);
			}
		},
		// 恢复删除
		resetDeleteFn(id){
			this.$confirm('您确定要将该功能恢复？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await RestoreDeleteData({ id: id,type:'Category' });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '恢复成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('恢复失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},
		// 删除功能
	  delClassFn(id,isDelted){
		let msg = isDelted?'彻底删除':'删除';
		this.$confirm('您将要'+msg+'该功能, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		  }).then(async () => {
			this.loading = true;
			try {
			   let res = await DeleteFunction({id:id,thoroughly:isDelted });
			   this.loading = false;
			   if(res.code === 200){
				  this.$message({
				  type: 'success',
				  message: '删除成功!'
				});
				this.getDataListFn();
			   }else{
				 this.$message.error('删除失败，错误信息：'+res.erroMessage);
			   }
			} catch (error) {
			  this.loading = false;
			  this.erroMessageShow(error);
			}
		  }).catch(() => {
			this.$message({
			  type: 'info',
			  message: '已取消删除'
			});  
		  });
	  },
		//  新增企业按钮点击
	  addClassOpen(){
		this.editClassTitle="新增功能";
		this.editClassDialog = true;
	  },
	//   功能icon上传成功
	  classIconUploadFn(val){
		this.editClassData.iconResourceId = val.local;
	  },
	//   功能icon删除
	  classIconRemoveFn(val){
		this.editClassData.iconResourceId = '';
	  },
	  // 保存功能基本信息
	  async saveClassInfoFn() {
		this.editClassLoading = true;
		if(!this.editClassData.name){
			this.editClassLoading = false;
			this.$message.error('请输入功能名称');
			return;
		}
		let res,msg;
		if(this.editClassTitle === '新增功能'){
			res = await AddFunction(this.editClassData);
			msg = '新增功能';
		}else{
			res = await UpdateFunction(this.editClassData);
			msg = '修改功能';
		}
		  this.editClassLoading = false;
		  if (res.code === 200) {
			this.$message.success(msg+'信息成功');
			this.editClassDialog  = false;
			this.getDataListFn();
		  } else {
			this.$message.error(msg+'失败，错误信息：' + res.erroMessage)
		  }
	  },
	  // 关闭编辑功能信息窗口
	  classDialogClose() {
		this.editClassData = {};
		this.editClassLoading = false;
	  },
	  async editClassBtnClick(data) {
		this.editClassTitle = '编辑功能';
		this.editClassData = data;
		this.editClassDialog = true;
	  },
	//   分页器变化
	  currentChange(val) {
		this.currentPage = val;
		this.getDataListFn();
	  },
	//   分页获取功能列表
	  async getDataListFn() {
		this.tableLoading = true;
		let params = {
		  Name: this.searchValue,
		}
		if(this.isDelete!=='all'){
			params.isDelete = this.isDelete;
		}
		try {
			const res = await GetAllFunctions(params);
			this.tableLoading = false;
			if (res.code === 200) {
				this.tabelData = res.data;
			} else {
				this.tabelData = [];
				this.$message.error('获取功能列表失败，错误信息：' + res.erroMessage);
			}
		} catch (error) {
			this.tableLoading = false;
			this.$message.error('请求发生错误：' + error);
		}
		
	  },
	}
  };
  </script>
  
  <style lang="scss" scoped>
  @media only screen and (min-width:992px){
	.category-list{
		overflow: hidden;
		width: 100%;
		flex-wrap: wrap;
		margin-top: 20px;
		min-height: 400px;
	}
	.category-item{
		width: 220px;
		box-shadow: 0px 0px 1px 2px rgba(6,0,1,0.1);
		background-color: #fff;
		border-radius: 16px;
		box-sizing: border-box;
		justify-content: center;
		flex-wrap: wrap;
		box-sizing: border-box;
		padding: 20px;
		margin: 10px 6px;
		
		&:hover{
			cursor: pointer;
		box-shadow: 0px 0px 18px 2px rgba(6,0,1,0.1);
		}
		.category-image{
			width: 80px;
			height: 80px;
			display: block;
		}
		.category-item-title{
			width: 100%;
			margin-top: 20px;
			overflow: hidden;
			white-space: nowrap;
			color: #333;
			p{
				margin: 0;
			}
		}
	}
}
@media only screen and (max-width:992px){
	.category-list{
		overflow: hidden;
		width: 100%;
		flex-wrap: wrap;
		margin-top: 20px;
	}
	.category-item{
		width: 100%;
		border: 1px solid #c2c2c2;
		margin: 4px 0;
		box-sizing: border-box;
		padding: 8px;
		.category-image{
			width: 40px;
			height: 40px;
			display: block;
			border-radius: 50%;
			box-sizing: border-box;
			padding: 2px;
			border: 1px solid #c2c2c2;
			margin-right: 10px;
		}
		&:hover{
			cursor: pointer;
			box-shadow: 0px 0px 18px 2px rgba(6,0,1,0.1);
		}
		
		.category-item-text{
			display: none;
		}
		.category-item-title:nth-of-type(1){
			flex:1;
			overflow: hidden;
		}
		.category-item-title:nth-of-type(2){
			display: none;
		}
		.category-item-title:nth-of-type(3){
			display: none;
		}
		.category-item-title:nth-last-child(1){
			margin-left: 20px;
			
		}
	}
}
  .prcoss-container {
	box-sizing: border-box;
	padding: 20px;
	background-color: #fff;
	.category-list{
		width: 100%;
	}
  }
  </style>